package com.qlh.camera

import com.qlh.camera.rgb.ImageUtil
import com.qlh.camera.voice.PlayLocalVoiceHelper
import com.qlh.camera.voice.PlayVoiceHelper
import com.sun.jna.Native
import com.sun.jna.NativeLong
import com.sun.jna.examples.win32.W32API
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.NativeLongByReference
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.io.File
import javax.swing.*
import javax.swing.border.BevelBorder
import javax.swing.border.SoftBevelBorder
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel


class CameraClient constructor(val interfaceSetting: InterfaceSetting) : JFrame() {

    //组件
    private val jSplitPaneHorizontal = JSplitPane() //默认水平分割面板[左右]
    private val jPanelUserInfo = JPanel()
    //预览
    private val jButtonRealPlay = JButton().apply {
        preferredSize = Dimension(0, 60)
    }
    //注册
    private val jButtonLogin = JButton().apply {
        preferredSize = Dimension(0, 60)
    }
    //拍照
    private val jButtonCamera = JButton().apply {
        preferredSize = Dimension(0, 100)

    }

    private val gap = JLabel().apply {
//        background = Color.BLUE
//        isOpaque = true
        preferredSize = Dimension(0, 10)
    }
    //标签
    private val jLabelUserName = JLabel() //用户名
    private val jLabelPortNumber = JLabel() //端口
    private val jLabelPassWord = JLabel() //密码
    private val jLabelIPAddress = JLabel() //IP地址
    private val jLabelCameraWidth = JLabel()//摄像头预览宽度
    private val jLabelCameraHeight = JLabel()//摄像头预览宽度
    //输入框
    private val jTextFieldPortNumber = JTextField()
    private val jTextFieldIPAddress = JTextField()
    private val jPasswordFieldPassword = JPasswordField()
    private val jTextFieldUserName = JTextField()

    private val jScrollPaneTree = JScrollPane()
    private val jTreeDevice = JTree()//设备树

    //图片预览
    private val picPre = JLabel()
    //private val picMtMsg = JLabel()

    private val mtLabel = JLabel().apply {
        text = "成熟程度："
        font = Font("",0,40)
        isVisible = false
    }
    private val mtContent = JLabel().apply {
        font = Font("",1,100)
        isOpaque = true//此句是重点，设置背景颜色必须先将它设置为不透明的，因为默认是透明
        background = Color.ORANGE
        foreground = Color.RED
    }
    private val positionLabel = JLabel().apply {
        text = "推荐位置："
        font = Font("",0,40)
        isVisible = false
    }
    private val positionContent = JLabel().apply {
        font = Font("",1,100)
        isOpaque = true//此句是重点，设置背景颜色必须先将它设置为不透明的，因为默认是透明
        background = Color.ORANGE
        foreground = Color.RED
    }

    private val jComboBoxCallback = JComboBox<Any>() //下拉列表组件
    private val jSplitPaneVertical = JSplitPane()//右侧预览分割面板[上下]
    private val jPanelRealplayArea = JPanel()
    private val panelRealplay = Panel()

    private val jScrollPanelAlarmList = JScrollPane()//预览底部通知信息
    private val jTableAlarm = JTable()

    //菜单
    private val jMenuBarConfig = JMenuBar()
    private val jMenuConfig = JMenu()
    private val jMenuItemBasicConfig = JMenuItem()


    private var m_strDeviceInfo = HCNetSDK.NET_DVR_DEVICEINFO_V30()//设备信息
    private var m_strIpparaCfg = HCNetSDK.NET_DVR_IPPARACFG()//IP参数
    private val m_strClientInfo = HCNetSDK.NET_DVR_CLIENTINFO()//用户参数

    private var bRealPlay = false //是否在预览
    private var m_sDeviceIP: String? = null //已登录设备的IP地址
    private var lUserID = NativeLong(-1)//用户句柄
    private var lPreviewHandle = NativeLong(-1)//预览句柄
    private var m_lPort = NativeLongByReference(NativeLong(-1))//回调预览时播放库端口指针
    private val fRealDataCallBack = FRealDataCallBack(panelRealplay, playControl, m_lPort)//预览回调函数实现
    //    val framePTZControl: JFramePTZControl? = null//云台控制窗口
    private var m_iTreeNodeNum = 0//通道树节点数目
    private val m_DeviceRoot = DefaultMutableTreeNode("设备")//通道树根节点

    private val configMap by lazy { FileUtil.getDefaultParams() }//配置参数

    companion object {
        private val dir = "hcSdk"
        val DLL_PATH = System.getProperty("java.io.tmpdir").let {
            val paths = it.split(File.separator)
            //取前2个目录
            paths[0] + File.separator + paths[1] + File.separator + dir + File.separator
        }
        val hCNetSDK = HCNetSDK.INSTANCE
        val playControl = PlayCtrl.INSTANCE
    }

    init {
        println("控件布局开始")
        initComponents()
        initMenu()
        getTodayHistory()
        println("控件布局完成")
        System.load("${DLL_PATH}opencv_java452.dll")
        //加载语音播放dll需要在启动的bat中修改
    }


    private fun initComponents() {
        defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE//退出程序
        addWindowListener(object : WindowAdapter() {
            override fun windowClosing(e: WindowEvent) {
                super.windowClosing(e)
                CommonUtil.windowsClose(object : ConfirmCallback {
                    override fun confirm() {
                        //如果程序在预览，停止预览,尤其是在回调预览选项下，防止崩溃
                        if (bRealPlay) {
                            jButtonRealPlayActionPerformed()
                        }
                        dispose()
                        PlayVoiceHelper.release()
                        println("退出程序")
                    }
                })
            }
        })
        title = "烤烟助手"
        val icon = ImageIcon("${DLL_PATH}resource/logo.png")
        iconImage = icon.image
        font = Font("宋体", 1, 20)
        jSplitPaneHorizontal.apply {
            border = BorderFactory.createEmptyBorder(1, 1, 1, 1)
            dividerLocation = interfaceSetting.getUserInfoDividerPosition() //分割线位置
            dividerSize = 2 //分割线宽度
        }

        //用户信息部分
        jPanelUserInfo.border = BorderFactory.createEtchedBorder(Color(255, 0, 0), null)
        jButtonRealPlay.apply {
            text = "开始预览"
            font = Font("",0,40)
            isFocusable = false
            addActionListener { jButtonRealPlayActionPerformed() }
        }

        jButtonLogin.apply {
            text = "设备注册"
            font = Font("",0,40)
            isFocusable = false
            addActionListener { jButtonLoginActionPerformed() }
        }

        jButtonCamera.apply {
            text = "拍照识别"
            font = Font("",0,60)
            isFocusable = false
            addActionListener { getDVRPic() }
        }

        jLabelIPAddress.text = "IP地址"
        jLabelUserName.text = "用户名"
        jLabelPortNumber.text = "端口"
        jLabelPassWord.text = "密码"

        jTextFieldIPAddress.text = "192.168.1.101"
        jTextFieldUserName.text = "admin"
        jPasswordFieldPassword.text = "caoyin520"
        jTextFieldPortNumber.text = "8000"
        //设备列表
        jTreeDevice.model = m_DeviceRoot.initialTreeModel()
        jScrollPaneTree.setViewportView(jTreeDevice)

        jComboBoxCallback.model = DefaultComboBoxModel<Any?>(arrayOf<String?>("直接预览", "回调预览"))

        val margin = (interfaceSetting.getUserInfoDividerPosition()*0.5 / 9f).toInt()
        val jPanelUserInfoLayout = GroupLayout(jPanelUserInfo)
        jPanelUserInfo.layout = jPanelUserInfoLayout
        jPanelUserInfoLayout.setHorizontalGroup(
                jPanelUserInfoLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(
                                jPanelUserInfoLayout.createSequentialGroup()//注册 预览 按钮
                                        .addGap(margin)
                                        .addComponent(jButtonLogin, GroupLayout.DEFAULT_SIZE,
                                                interfaceSetting.getUserInfoDividerPosition() / 3,
                                                interfaceSetting.getUserInfoDividerPosition() / 3)
                                        //.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGap(margin)
                                        .addComponent(jButtonRealPlay, GroupLayout.DEFAULT_SIZE,
                                                interfaceSetting.getUserInfoDividerPosition() / 3,
                                                interfaceSetting.getUserInfoDividerPosition() / 3)
//                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
//                                        .addComponent(jButtonCamera)
                                        .addGap(margin)
                        )
                        .addComponent(jButtonCamera, interfaceSetting.getUserInfoDividerPosition() - 5,
                                GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE)
                        .addComponent(gap, interfaceSetting.getUserInfoDividerPosition() - 5,
                                GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE)
//                        .addGroup(
//                                jPanelUserInfoLayout.createSequentialGroup() //IP
//                                        .addView(jLabelIPAddress, jTextFieldIPAddress)
//                        )
//                        .addGroup( //创建串行组
//                                jPanelUserInfoLayout.createSequentialGroup() //用户名
//                                        .addView(jLabelUserName, jTextFieldUserName)
//                        )
//                        .addGroup(
//                                jPanelUserInfoLayout.createSequentialGroup() //密码
//                                        .addView(jLabelPassWord, jPasswordFieldPassword, b2 = 30)
//                        )
//                        .addGroup(
//                                jPanelUserInfoLayout.createSequentialGroup()//端口
//                                        .addView(jLabelPortNumber, jTextFieldPortNumber, b2 = 30)
//                        )
//                        .addGroup(
//                                jPanelUserInfoLayout.createSequentialGroup()//注册 预览 按钮
//                                        .addContainerGap()
//                                        .addComponent(jButtonLogin)
//                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
//                                        .addComponent(jButtonRealPlay)
//                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
//                                        .addComponent(jButtonCamera)
//                        )
                        //设备列表
                        //.addComponent(jScrollPaneTree, GroupLayout.DEFAULT_SIZE, 150, GroupLayout.DEFAULT_SIZE)
                        //图片
                        .addComponent(picPre, GroupLayout.DEFAULT_SIZE, 150, GroupLayout.DEFAULT_SIZE)
                        //.addComponent(picMtMsg, GroupLayout.DEFAULT_SIZE, 150, GroupLayout.DEFAULT_SIZE)
                        .addGroup(
                                jPanelUserInfoLayout.createSequentialGroup()
                                        .addGap(15)
                                        .addComponent(mtLabel)
                                        .addComponent(mtContent)
                        )

                        .addGroup(
                                jPanelUserInfoLayout.createSequentialGroup()
                                        .addGap(15)
                                        .addComponent(positionLabel)
                                        .addComponent(positionContent)
                        )
//                        //预览选项
//                        .addGroup(jPanelUserInfoLayout.createSequentialGroup()
//                                .addContainerGap()
//                                .addComponent(jComboBoxCallback, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
//                                .addContainerGap(66, Short.MAX_VALUE.toInt())
//                        )
//                        .addGroup(
//                                GroupLayout.Alignment.TRAILING,
//                                jPanelUserInfoLayout.createSequentialGroup()
//                                        .addContainerGap(83, Short.MAX_VALUE.toInt())
//                                        .addContainerGap()
//                        )
        )
        jPanelUserInfoLayout.setVerticalGroup(
                jPanelUserInfoLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(jPanelUserInfoLayout.createSequentialGroup()
                                .addGap(18)
                                .addView(jPanelUserInfoLayout, jButtonLogin, jButtonRealPlay)
                                .addGap(18)
                                .addComponent(jButtonCamera, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
//                                .addGap(9, 9, 9)
                                .addGap(5)
                                .addComponent(gap, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
//                                .addView(jPanelUserInfoLayout, jLabelIPAddress, jTextFieldIPAddress)
//                                .addGap(9, 9, 9)
//                                .addView(jPanelUserInfoLayout, jLabelUserName, jTextFieldUserName)
//                                .addGap(9, 9, 9)
//                                .addView(jPanelUserInfoLayout, jLabelPassWord, jPasswordFieldPassword)
//                                .addGap(9, 9, 9)
//                                .addView(jPanelUserInfoLayout, jLabelPortNumber, jTextFieldPortNumber)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                //.addView(jPanelUserInfoLayout, jButtonLogin, jButtonRealPlay, jButtonCamera)
                                //.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                //.addComponent(jScrollPaneTree, GroupLayout.DEFAULT_SIZE, 404, GroupLayout.PREFERRED_SIZE)
                                //.addGap(18, 18, 18)
                                .addComponent(picPre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                .addGap(30)
                                //.addComponent(picMtMsg, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
//                                .addComponent(jComboBoxCallback, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                //.addGap(150)
                                .addView(jPanelUserInfoLayout,mtLabel,mtContent)
                                .addGap(20)
                                .addView(jPanelUserInfoLayout,positionLabel,positionContent)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                //.addContainerGap()
                        )
        )
        //为左右面板添加组件
        jSplitPaneHorizontal.leftComponent = jPanelUserInfo

        //val dim = Toolkit.getDefaultToolkit().screenSize
        jSplitPaneVertical.dividerLocation = interfaceSetting.getPreViewDividerPosition(this)
        jSplitPaneVertical.dividerSize = 2
        jSplitPaneVertical.orientation = JSplitPane.VERTICAL_SPLIT
        jPanelRealplayArea.border = BorderFactory.createLineBorder(Color(153, 255, 102))
        panelRealplay.addMouseListener(object : MouseAdapter() {
            override fun mousePressed(evt: MouseEvent) {
                panelRealplayMousePressed(evt)
            }
        })
        val panelRealplayLayout = GroupLayout(panelRealplay)
        panelRealplay.layout = panelRealplayLayout
        panelRealplayLayout.setHorizontalGroup(
                panelRealplayLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGap(0, 704, Short.MAX_VALUE.toInt())
        )
        panelRealplayLayout.setVerticalGroup(
                panelRealplayLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGap(0, 576, Short.MAX_VALUE.toInt())
        )
        val jPanelRealplayAreaLayout = GroupLayout(jPanelRealplayArea)
        jPanelRealplayArea.layout = jPanelRealplayAreaLayout
        jPanelRealplayAreaLayout.setHorizontalGroup(
                jPanelRealplayAreaLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(panelRealplay, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt())
        )
        jPanelRealplayAreaLayout.setVerticalGroup(
                jPanelRealplayAreaLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(panelRealplay, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt())
        )
        jSplitPaneVertical.topComponent = jPanelRealplayArea//预览部分
        jScrollPanelAlarmList.border = BorderFactory.createEtchedBorder()
        jTableAlarm.model = this.initialTableModel()
        jTableAlarm.setParams()
        jScrollPanelAlarmList.setViewportView(jTableAlarm)

        jSplitPaneVertical.bottomComponent = jScrollPanelAlarmList//底部通知信息

        jSplitPaneHorizontal.rightComponent = jSplitPaneVertical//右部分

        // 为指定的 Container 创建 GroupLayout
        val layout = GroupLayout(contentPane)
        contentPane.layout = layout
        layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(jSplitPaneHorizontal, GroupLayout.DEFAULT_SIZE, 866, Short.MAX_VALUE.toInt())
        )
        layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(jSplitPaneHorizontal, GroupLayout.DEFAULT_SIZE, 671, Short.MAX_VALUE.toInt())
        )
        pack()
    }

    private fun initMenu() {
        jMenuBarConfig.border = SoftBevelBorder(BevelBorder.RAISED)
        jMenuConfig.text = "基础配置"
        jMenuItemBasicConfig.apply {
            text = "参数配置"
            addMouseListener(object : MouseAdapter() {
                override fun mousePressed(e: MouseEvent?) {
                    super.mousePressed(e)
                    val msg = "欠熟，推荐区域 1 2 3，假熟，推荐区域 1 2 3，成熟，推荐区域 4 5 6，过熟，推荐区域 7 8 9"
                    PlayVoiceHelper.playText(msg)
                    //PlayLocalVoiceHelper.playFile()
                    CommonUtil.showDlgAndInput(this@CameraClient)
                }
            })
        }
        jMenuConfig.add(jMenuItemBasicConfig)
        jMenuBarConfig.add(jMenuConfig)

        jMenuBar = jMenuBarConfig
    }

    /*************************************************
     * 函数:      "注册"  按钮单击响应函数
     * 函数描述:	注册登录设备
     */
    private fun jButtonLoginActionPerformed() {
        //val loading = startLoading()
        if (configMap.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请配置基础参数")
            return
        }
        //注册之前先注销已注册的用户,预览情况下不可注销
        if (bRealPlay) {
            JOptionPane.showMessageDialog(this, "注册新用户请先停止当前预览!")
            return
        }

        if (lUserID.toLong() > -1) { //先注销
            hCNetSDK.NET_DVR_Logout_V30(lUserID)
            lUserID = NativeLong(-1)
            m_iTreeNodeNum = 0
            m_DeviceRoot.removeAllChildren()
        }
        //注册
        m_sDeviceIP = configMap["ip"] //设备ip地址
        m_strDeviceInfo = HCNetSDK.NET_DVR_DEVICEINFO_V30()
        val iPort = configMap["port"]?.toInt() ?: 0
        lUserID = hCNetSDK.NET_DVR_Login_V30(m_sDeviceIP,
                iPort.toShort(), configMap["name"] ?: "", configMap["pwd"] ?: "", m_strDeviceInfo)
        val userID: Long = lUserID.toLong()
        if (userID == -1L) {
            m_sDeviceIP = "" //登录未成功,IP置为空
            JOptionPane.showMessageDialog(this, "注册失败")
        } else {
            //jTableAlarm.addInfo(jTextFieldIPAddress.text, "注册成功")
            createDeviceTree()
            //注册成功直接预览
            jButtonRealPlayActionPerformed()
        }
        //loading.stop()
    }

    /*************************************************
     * 函数:      "预览"  按钮单击响应函数
     * 函数描述:	获取通道号,打开播放窗口,开始此通道的预览
     */
    private fun jButtonRealPlayActionPerformed() {
        println(panelRealplay.width)
        println(panelRealplay.height)
        if (lUserID.toInt() == -1) {
            JOptionPane.showMessageDialog(this, "请先注册")
            return
        }
        //如果预览窗口没打开,不在预览
        if (!bRealPlay) { //获取窗口句柄
            val hwnd = W32API.HWND(Native.getComponentPointer(panelRealplay))
            //获取通道号
            val iChannelNum: Int = jTreeDevice.getChannelNumber() //通道号
            if (iChannelNum == -1) {
                JOptionPane.showMessageDialog(this, "请选择要预览的通道")
                return
            }
            //m_strClientInfo = HCNetSDK.NET_DVR_CLIENTINFO()
            //val loading = startLoading()
            m_strClientInfo.lChannel = NativeLong(iChannelNum.toLong())
            //在此判断是否回调预览,0,不回调 1 回调
            if (jComboBoxCallback.selectedIndex == 0) {
                m_strClientInfo.hPlayWnd = hwnd
                lPreviewHandle = hCNetSDK.NET_DVR_RealPlay_V30(lUserID,
                        m_strClientInfo, null, null, true)
            } else if (jComboBoxCallback.selectedIndex == 1) {
                m_strClientInfo.hPlayWnd = null
                lPreviewHandle = hCNetSDK.NET_DVR_RealPlay_V30(lUserID,
                        m_strClientInfo, fRealDataCallBack, null, true)
            }
            val previewSucValue: Long = lPreviewHandle.toLong()
            //loading.stop()
            //预览失败时:
            if (previewSucValue == -1L) {
                JOptionPane.showMessageDialog(this, "预览失败")
                return
            }
            //预览成功的操作
            //jTableAlarm.addInfo(jTextFieldIPAddress.text, "预览成功")
            jButtonRealPlay.text = "停止预览"
            bRealPlay = true
            //显示云台控制窗口
//            framePTZControl = JFramePTZControl(lPreviewHandle)
//            framePTZControl.setLocation(x + width, y)
//            framePTZControl.setVisible(true)
        } else {
            //jTableAlarm.addInfo(jTextFieldIPAddress.text, "停止预览")
            hCNetSDK.NET_DVR_StopRealPlay(lPreviewHandle)
            jButtonRealPlay.text = "开始预览"
            bRealPlay = false
            if (m_lPort.getValue().toInt() != -1) {
                playControl.PlayM4_Stop(m_lPort.getValue())
                m_lPort.setValue(NativeLong(-1))
            }
            //framePTZControl.dispose()
            panelRealplay.repaint()
        }
    }

    /*************************************************
     * 函数:    CreateDeviceTree
     * 函数描述:建立设备通道数
     */
    private fun createDeviceTree() {
        val ibrBytesReturned = IntByReference(0) //获取IP接入配置参数
        var bRet: Boolean
        m_strIpparaCfg = HCNetSDK.NET_DVR_IPPARACFG()
        m_strIpparaCfg.write()
        val lpIpParaConfig = m_strIpparaCfg.pointer
        bRet = hCNetSDK.NET_DVR_GetDVRConfig(lUserID, HCNetSDK.NET_DVR_GET_IPPARACFG, NativeLong(0), lpIpParaConfig, m_strIpparaCfg.size(), ibrBytesReturned)
        m_strIpparaCfg.read()
        val TreeModel = jTreeDevice.model as DefaultTreeModel //获取树模型
        if (!bRet) { //设备不支持,则表示没有IP通道
            for (iChannum in 0 until m_strDeviceInfo.byChanNum) {
                val newNode = DefaultMutableTreeNode("Camera" + (iChannum + m_strDeviceInfo.byStartChan))
                TreeModel.insertNodeInto(newNode, m_DeviceRoot, iChannum)
            }
        } else { //设备支持IP通道
            for (iChannum in 0 until m_strDeviceInfo.byChanNum) {
                if (m_strIpparaCfg.byAnalogChanEnable[iChannum].toInt() == 1) {
                    val newNode = DefaultMutableTreeNode("Camera" + (iChannum + m_strDeviceInfo.byStartChan))
                    TreeModel.insertNodeInto(newNode, m_DeviceRoot, m_iTreeNodeNum)
                    m_iTreeNodeNum++
                }
            }
            for (iChannum in 0 until HCNetSDK.MAX_IP_CHANNEL)
                if (m_strIpparaCfg.struIPChanInfo[iChannum].byEnable.toInt() == 1) {
                    val newNode = DefaultMutableTreeNode("IPCamera" + (iChannum + m_strDeviceInfo.byStartChan))
                    TreeModel.insertNodeInto(newNode, m_DeviceRoot, m_iTreeNodeNum)
                }
        }
        TreeModel.reload() //将添加的节点显示到界面
        jTreeDevice.setSelectionInterval(1, 1) //选中第一个节点
    }

    /*************************************************
     * 函数:      "播放窗口"  双击响应函数
     * 函数描述:   双击全屏预览当前预览通道
     */
    private fun panelRealplayMousePressed(evt: MouseEvent) {
        if (!bRealPlay) {
            return
        }
        //鼠标单击事件为双击
        if (evt.clickCount == 2) { //新建JWindow 全屏预览
            val wnd = JWindow()
            //获取屏幕尺寸
            val screenSize = Toolkit.getDefaultToolkit().screenSize
            wnd.size = screenSize
            wnd.isVisible = true
            val hwnd = W32API.HWND(Native.getComponentPointer(wnd))
            m_strClientInfo.hPlayWnd = hwnd
            val lRealHandle: NativeLong = hCNetSDK.NET_DVR_RealPlay_V30(lUserID,
                    m_strClientInfo, null, null, true)
            //JWindow增加双击响应函数,双击时停止预览,退出全屏
            wnd.addMouseListener(object : MouseAdapter() {
                override fun mousePressed(evt: MouseEvent) {
                    if (evt.clickCount == 2) { //停止预览
                        hCNetSDK.NET_DVR_StopRealPlay(lRealHandle)
                        wnd.dispose()
                    }
                }
            })
        }
    }

    /**拍照保存**/
    private fun getDVRPic() {
        if (lUserID.toInt() == -1) {
            JOptionPane.showMessageDialog(this, "请注册设备")
            return
        }
        if (!bRealPlay) {
            JOptionPane.showMessageDialog(this, "没有开启预览")
            return
        }
        val loading = startLoading()
        //JPEG图像信息结构体
        val jpeg = HCNetSDK.NET_DVR_JPEGPARA().apply {
            /* 0=CIF, 1=QCIF, 2=D1 3=UXGA(1600x1200), 4=SVGA(800x600), 5=HD720p(1280x720),6=VGA*/
            wPicSize = 2// 设置图片的分辨率
            /* 图片质量系数 0-最好 1-较好 2-一般 */
            wPicQuality = 0// 设置图片质量
        }

        //创建图片目录
        val path = FileUtil.getPicPath()
        //抓图到文件
        val channel = jTreeDevice.getChannelNumber().toLong()//通道
        val success = hCNetSDK.NET_DVR_CaptureJPEGPicture(lUserID, NativeLong(channel), jpeg, path)
        if (success) {
            //拍照成功进行处理获取成熟度
            showPic(path)
            val mtbo = ImageUtil.getKeyAreaMt(path)
            val result = jTableAlarm.addInfo(mtbo.name, mtbo.position, path)
//            picMtMsg.apply {
//                text = "<html>成熟度：<font color = \"#FF0000\" size=\"60\">${mtbo.name}</font><br><br>推荐位置：<font color = \"#FF0000\" size=\"90\">${mtbo.position}</font></html>"
//                isOpaque = true//此句是重点，设置背景颜色必须先将它设置为不透明的，因为默认是透明
//                background = Color.ORANGE
//                border = EmptyBorder(50, 10, 50, 10)
//                //font = Font("dialog",1,60)
//            }
            mtLabel.isVisible = true
            positionLabel.isVisible = true
            mtContent.text = mtbo.name
            positionContent.text = mtbo.position
            FileUtil.saveResult(result)
            val msg = "${mtbo.name},推荐区域${mtbo.position}"
            PlayVoiceHelper.playText(msg)

        } else {
            println("抓取失败")
            //jTableAlarm.addInfo(jTextFieldIPAddress.text, "抓取失败：${hCNetSDK.NET_DVR_GetLastError()}")
        }
        loading.stop()
    }


    private fun showPic(path: String) {
        var icon = ImageIcon(path)
        //等比缩放条件
        val imgWidth = icon.iconWidth
        val imgHeight = icon.iconHeight
        val conWidth = interfaceSetting.getUserInfoDividerPosition()
        val conHeight = (imgHeight * conWidth) / imgWidth
        picPre.apply {
            //此句是重点，设置背景颜色必须先将它设置为不透明的，因为默认是透明
            preferredSize = Dimension(conWidth, conHeight)
            isOpaque = true
            background = Color.BLACK
        }
        val reImgWidth: Int
        val reImgHeight: Int
        if (imgWidth / imgHeight >= conWidth / conHeight) {
            if (imgWidth > conWidth) {
                reImgWidth = conWidth
                reImgHeight = imgHeight * reImgWidth / imgWidth
            } else {
                reImgWidth = imgWidth
                reImgHeight = imgHeight
            }
        } else {
            if (imgWidth > conWidth) {
                reImgHeight = conHeight
                reImgWidth = imgWidth * reImgHeight / imgHeight
            } else {
                reImgWidth = imgWidth
                reImgHeight = imgHeight
            }
        }

        icon = ImageIcon(icon.image.getScaledInstance(reImgWidth, reImgHeight, Image.SCALE_DEFAULT))
        picPre.icon = icon
        picPre.horizontalAlignment = SwingConstants.CENTER

    }

    private fun getTodayHistory(){
      FileUtil.getHistory().forEach {
          jTableAlarm.addInfo(it.mt,it.area,it.path,it.time)
      }

    }
}